/*
 * Copyright (c) 2013, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package pyip.lib.mixtool.util;

/**
 * @author yepeng
 * @date 2015年9月17日
 */
public class HashTool {
    public static void main(String[] args) {
        System.out.println(hashHex(6));
        System.out.println(hashHex(8));
        System.out.println(hashHex(18));
        System.out.println();
        System.out.println(hashOctal(6));
        System.out.println(hashOctal(8));
        System.out.println(hashOctal(18));

    }

    /**
     * @param bits
     * @return max bit 11
     */
    public static String hashOctal(int bits) {
        String hexString = Integer.toOctalString(randomInt());
        int offset = 11 - bits > 0 ? 11 - bits : 0;
        if (offset > 0) {
            hexString = hexString.substring(offset);
        } else {
            offset = 11;
        }

        if (bits > 11) {
            bits = 11;
        }
        return hexString.length() == bits ? hexString : hexString + "0";
    }

    /**
     * @param bits
     * @return max bit 8
     */
    public static String hashHex(int bits) {
        String hexString = Integer.toHexString(randomInt());
        int offset = 8 - bits > 0 ? 8 - bits : 0;
        if (offset > 0) {
            return hexString.substring(offset);
        }
        return hexString;
    }

    // TODO 使用Random函数
    private static int randomInt() {
        int base = (int) (System.currentTimeMillis() & Integer.MAX_VALUE);
        int reverse = Integer.reverse(base);
        return base + reverse;
    }
}
